﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using MultiDAQ_Analysis.Util;
using MultiDAQ_Analysis.Models;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// 所有通道测量结果汇总查看窗口
    /// 展示所有通道各种测量类型的结果汇总，不显示详细数据
    /// </summary>
    public class AllChannelsMeasurementResultsForm : UIForm
    {
        #region 字段定义
        private UIRichTextBox txtSummaryDisplay;
        private UIButton btnDownloadSummary;
        private UIButton btnPrint;
        private UIButton btnRefresh;
        private UILabel lblTitleInfo;
        private int channelCount = AppConfig.ChannelCount;

        // 打印相关字段
        private PrintDocument printDocument;
        private string[] printLines;
        private int printLineIndex;

        // 测量类型映射
        private static readonly Dictionary<string, string> MeasurementTypeNames = new Dictionary<string, string>
        {
            {"Background", "本底测量"},
            {"WorkingSourceEfficiency", "工作源效率测量"},
            {"StandardSourceEfficiency", "标准源效率测量"},
            {"WaterSample", "水样品测量"},
            {"BioSample", "生物样品测量"},
            {"GasSample", "气体样品测量"},
            {"EnvSample", "环境样品测量"}
        };
        #endregion

        #region 构造函数和初始化
        public AllChannelsMeasurementResultsForm()
        {
            InitializeForm();
            SetupForm();
            InitializePrintDocument();
            _ = LoadMeasurementResultsSummaryAsync(); // 异步加载，不等待
        }

        /// <summary>
        /// 初始化窗体基本属性
        /// </summary>
        private void InitializeForm()
        {
            this.SuspendLayout();

            // 设置窗体基本属性
            this.Text = "所有通道测量结果汇总";
            this.Size = new Size(1000, 700);
            this.StartPosition = FormStartPosition.CenterParent;
            this.ShowInTaskbar = false;
            this.MaximizeBox = true;
            this.MinimizeBox = false;
            this.Name = "AllChannelsMeasurementResultsForm";

            this.ResumeLayout(false);
        }

        /// <summary>
        /// 初始化打印文档
        /// </summary>
        private void InitializePrintDocument()
        {
            printDocument = new PrintDocument();
            printDocument.PrintPage += PrintDocument_PrintPage;
            printDocument.DocumentName = "测量结果汇总报告";
        }

        private void SetupForm()
        {
            // 创建主布局
            var mainLayout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 1,
                RowCount = 3,
                Padding = new Padding(15)
            };

            // 设置行样式
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60)); // 标题和按钮区
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // 内容区
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60)); // 底部按钮区

            // 创建标题区面板
            var titlePanel = CreateTitlePanel();
            mainLayout.Controls.Add(titlePanel, 0, 0);

            // 创建内容显示区
            txtSummaryDisplay = new UIRichTextBox
            {
                Dock = DockStyle.Fill,
                Font = new Font("Consolas", 9.5F),
                ReadOnly = true,
                BackColor = Color.White
            };
            mainLayout.Controls.Add(txtSummaryDisplay, 0, 1);

            // 创建底部按钮区
            var buttonPanel = CreateButtonPanel();
            mainLayout.Controls.Add(buttonPanel, 0, 2);

            this.Controls.Add(mainLayout);
        }

        private Panel CreateTitlePanel()
        {
            var titlePanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 60,
                BackColor = Color.FromArgb(243, 249, 255)
            };

            lblTitleInfo = new UILabel
            {
                Text = $"所有通道测量结果汇总 ({channelCount} 个通道)",
                AutoSize = true,
                Font = new Font("微软雅黑", 14F, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 158, 255),
                Location = new Point(20, 18)
            };

            btnRefresh = new UIButton
            {
                Text = "刷新数据",
                Size = new Size(100, 35),
                FillColor = Color.FromArgb(64, 158, 255),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Top | AnchorStyles.Right
            };
            btnRefresh.Click += BtnRefresh_Click;

            titlePanel.Controls.Add(lblTitleInfo);
            titlePanel.Controls.Add(btnRefresh);

            // 处理窗体大小变化时按钮位置调整
            titlePanel.SizeChanged += (s, e) =>
            {
                btnRefresh.Location = new Point(titlePanel.Width - 120, 13);
            };

            return titlePanel;
        }

        private Panel CreateButtonPanel()
        {
            var buttonPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 60
            };

            btnDownloadSummary = new UIButton
            {
                Text = "导出",
                Size = new Size(100, 40),
                FillColor = Color.FromArgb(103, 194, 58),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnDownloadSummary.Click += BtnDownloadSummary_Click;

            btnPrint = new UIButton
            {
                Text = "打印",
                Size = new Size(100, 40),
                FillColor = Color.FromArgb(24, 144, 255),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnPrint.Click += BtnPrint_Click;

            var btnClose = new UIButton
            {
                Text = "关闭",
                Size = new Size(80, 40),
                FillColor = Color.FromArgb(255, 87, 87),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnClose.Click += (s, e) => this.Close();

            buttonPanel.Controls.Add(btnDownloadSummary);
            buttonPanel.Controls.Add(btnPrint);
            buttonPanel.Controls.Add(btnClose);

            // 处理窗体大小变化时按钮位置调整
            buttonPanel.SizeChanged += (s, e) =>
            {
                btnDownloadSummary.Location = new Point(buttonPanel.Width - 320, 10);
                btnPrint.Location = new Point(buttonPanel.Width - 210, 10);
                btnClose.Location = new Point(buttonPanel.Width - 90, 10);
            };

            return buttonPanel;
        }
        #endregion

        #region 数据加载和生成
        /// <summary>
        /// 加载所有通道的测量结果汇总
        /// </summary>
        private async Task LoadMeasurementResultsSummaryAsync()
        {
            try
            {
                // 显示加载提示
                if (txtSummaryDisplay != null)
                {
                    txtSummaryDisplay.Text = "正在加载测量结果汇总数据，请稍候...";
                }

                if (btnRefresh != null)
                {
                    btnRefresh.Enabled = false;
                    btnRefresh.Text = "加载中...";
                }

                var summaryData = await GenerateMeasurementResultsSummary();

                if (txtSummaryDisplay != null)
                {
                    txtSummaryDisplay.Text = summaryData;
                }
            }
            catch (Exception ex)
            {
                var errorMessage = $"加载测量结果汇总时发生错误：{ex.Message}";
                if (txtSummaryDisplay != null)
                {
                    txtSummaryDisplay.Text = errorMessage;
                }
                UIMessageBox.ShowError($"加载测量结果汇总失败：{ex.Message}");
            }
            finally
            {
                if (btnRefresh != null)
                {
                    btnRefresh.Enabled = true;
                    btnRefresh.Text = "刷新数据";
                }
            }
        }

        /// <summary>
        /// 生成测量结果汇总数据
        /// </summary>
        private async Task<string> GenerateMeasurementResultsSummary()
        {
            var sb = new StringBuilder();
            sb.AppendLine("=== 所有通道测量结果汇总报告 ===");
            sb.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine($"通道总数: {channelCount}");
            sb.AppendLine();

            try
            {
                // 收集所有通道的测量数据
                var allMeasurementData = await CollectAllChannelsMeasurementData();

                // 生成各测量类型完成情况汇总
                GenerateMeasurementTypesSummary(sb, allMeasurementData);

                // 生成最新测量结果汇总表格
                GenerateLatestResultsTable(sb, allMeasurementData);

                // 生成统计分析
                GenerateStatisticalAnalysis(sb, allMeasurementData);

                // 生成测量历史概览
                //GenerateMeasurementHistory(sb, allMeasurementData);
            }
            catch (Exception ex)
            {
                sb.AppendLine($"生成汇总数据时发生错误：{ex.Message}");
                sb.AppendLine("请检查数据完整性或联系系统管理员。");
            }

            return sb.ToString();
        }

        /// <summary>
        /// 收集所有通道的测量数据
        /// </summary>
        private async Task<Dictionary<int, Dictionary<string, MultiRoundMeasurementData>>> CollectAllChannelsMeasurementData()
        {
            var allData = new Dictionary<int, Dictionary<string, MultiRoundMeasurementData>>();

            for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
            {
                var channelData = new Dictionary<string, MultiRoundMeasurementData>();

                foreach (var measurementType in MeasurementTypeNames.Keys)
                {
                    try
                    {
                        var data = await ChannelBasedJsonDataManager.GetChannelMeasurementAsync(channelIndex, measurementType);
                        if (data != null)
                        {
                            channelData[measurementType] = data;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"获取通道 {channelIndex + 1} 的 {measurementType} 数据失败: {ex.Message}");
                    }
                }

                allData[channelIndex] = channelData;
            }

            return allData;
        }

        /// <summary>
        /// 生成各测量类型完成情况汇总
        /// </summary>
        private void GenerateMeasurementTypesSummary(StringBuilder sb, Dictionary<int, Dictionary<string, MultiRoundMeasurementData>> allData)
        {
            sb.AppendLine("【各测量类型完成情况】");
            sb.AppendLine($"{"测量类型",-20} {"完成通道数",-10} {"总轮数",-8} {"最新测量时间",-20}");
            sb.AppendLine(new string('-', 70));

            foreach (var typeKvp in MeasurementTypeNames)
            {
                string measurementType = typeKvp.Key;
                string displayName = typeKvp.Value;

                int completedChannels = 0;
                int totalRounds = 0;
                DateTime latestTime = DateTime.MinValue;

                foreach (var channelData in allData.Values)
                {
                    if (channelData.ContainsKey(measurementType))
                    {
                        completedChannels++;
                        totalRounds += channelData[measurementType].TotalRounds;
                        if (channelData[measurementType].StartTime > latestTime)
                        {
                            latestTime = channelData[measurementType].StartTime;
                        }
                    }
                }

                string latestTimeStr = latestTime == DateTime.MinValue ? "无" : latestTime.ToString("MM-dd HH:mm");
                sb.AppendLine($"{displayName,-20} {completedChannels}/{channelCount,-9} {totalRounds,-8} {latestTimeStr,-20}");
            }
            sb.AppendLine();
        }

        /// <summary>
        /// 生成最新测量结果汇总表格
        /// </summary>
        private void GenerateLatestResultsTable(StringBuilder sb, Dictionary<int, Dictionary<string, MultiRoundMeasurementData>> allData)
        {
            sb.AppendLine("【最新测量结果汇总】");
            sb.AppendLine($"{"通道",-6} {"本底",-12} {"工作源",-12} {"标准源",-12} {"水样品",-12} {"生物",-12} {"气体",-12} {"环境",-12}");
            sb.AppendLine(new string('-', 90));

            for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
            {
                var channelData = allData[channelIndex];
                sb.Append($"CH{channelIndex + 1,-5} ");

                foreach (string measurementType in new[] { "Background", "WorkingSourceEfficiency", "StandardSourceEfficiency", "WaterSample", "BioSample", "GasSample", "EnvSample" })
                {
                    string resultStr = "---";
                    if (channelData.ContainsKey(measurementType))
                    {
                        var data = channelData[measurementType];
                        if (data.ChannelResults.ContainsKey(channelIndex) && data.ChannelResults[channelIndex].AverageResult != null)
                        {
                            var avgResult = data.ChannelResults[channelIndex].AverageResult;
                            // 显示α结果（保留3位小数）
                            resultStr = avgResult.AlphaResult.ToString("F3");
                            if (resultStr.Length > 8) resultStr = resultStr.Substring(0, 8) + "…";
                        }
                        else
                        {
                            resultStr = "完成";
                        }
                    }
                    sb.Append($"{resultStr,-12} ");
                }
                sb.AppendLine();
            }
            sb.AppendLine();
        }

        /// <summary>
        /// 生成统计分析
        /// </summary>
        private void GenerateStatisticalAnalysis(StringBuilder sb, Dictionary<int, Dictionary<string, MultiRoundMeasurementData>> allData)
        {
            sb.AppendLine("【统计分析】");

            // 计算总体统计
            int totalMeasurements = allData.Values.SelectMany(cd => cd.Values).Count();
            int totalRounds = allData.Values.SelectMany(cd => cd.Values).Sum(data => data.TotalRounds);
            var totalDuration = allData.Values.SelectMany(cd => cd.Values)
                .Sum(data => (data.EndTime - data.StartTime).TotalMinutes);

            sb.AppendLine($"├─ 总测量次数: {totalMeasurements}");
            sb.AppendLine($"├─ 总测量轮数: {totalRounds}");
            sb.AppendLine($"├─ 总测量时长: {totalDuration:F1} 分钟 ({totalDuration / 60:F1} 小时)");

            // 各通道完成度统计
            var channelCompletions = new List<int>();
            for (int i = 0; i < channelCount; i++)
            {
                channelCompletions.Add(allData[i].Count);
            }

            if (channelCompletions.Count > 0)
            {
                double avgCompletion = channelCompletions.Average();
                int maxCompletion = channelCompletions.Max();
                int minCompletion = channelCompletions.Min();

                sb.AppendLine($"├─ 通道平均完成度: {avgCompletion:F1} / {MeasurementTypeNames.Count}");
                sb.AppendLine($"├─ 最大完成度: {maxCompletion} / {MeasurementTypeNames.Count}");
                sb.AppendLine($"└─ 最小完成度: {minCompletion} / {MeasurementTypeNames.Count}");
            }
            sb.AppendLine();
        }

        /// <summary>
        /// 生成测量历史概览
        /// </summary>
        private void GenerateMeasurementHistory(StringBuilder sb, Dictionary<int, Dictionary<string, MultiRoundMeasurementData>> allData)
        {
            sb.AppendLine("【测量历史概览】");

            var allMeasurements = allData.Values.SelectMany(cd => cd.Values)
                .OrderByDescending(data => data.StartTime)
                .Take(10); // 显示最近10次测量

            sb.AppendLine($"{"序号",-4} {"测量类型",-20} {"通道",-6} {"轮数",-6} {"开始时间",-16} {"耗时(分)",-8}");
            sb.AppendLine(new string('-', 70));

            int index = 1;
            foreach (var measurement in allMeasurements)
            {
                string displayName = GetMeasurementTypeDisplayName(measurement.MeasurementType);
                int channelIndex = measurement.ChannelResults.Keys.FirstOrDefault();
                double duration = (measurement.EndTime - measurement.StartTime).TotalMinutes;

                sb.AppendLine($"{index,-4} {displayName,-20} CH{channelIndex + 1,-5} {measurement.TotalRounds,-6} " +
                             $"{measurement.StartTime:MM-dd HH:mm,-16} {duration,-8:F1}");
                index++;
            }

            sb.AppendLine();
            sb.AppendLine("注：仅显示最近10次测量记录");
        }

        /// <summary>
        /// 获取测量类型显示名称
        /// </summary>
        private string GetMeasurementTypeDisplayName(string measurementType)
        {
            return MeasurementTypeNames.ContainsKey(measurementType)
                ? MeasurementTypeNames[measurementType]
                : measurementType;
        }
        #endregion

        #region 打印相关方法
        /// <summary>
        /// 打印文档的PrintPage事件处理
        /// </summary>
        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                // 设置打印字体和边距
                Font printFont = new Font("宋体", 9F);
                Font titleFont = new Font("宋体", 12F, FontStyle.Bold);
                float leftMargin = e.MarginBounds.Left;
                float topMargin = e.MarginBounds.Top;
                float yPos = topMargin;
                float lineHeight = printFont.GetHeight(e.Graphics);

                // 打印标题
                string title = $"所有通道测量结果汇总报告 - 第{((printLineIndex == 0) ? 1 : (printLineIndex / 50 + 1))}页";
                e.Graphics.DrawString(title, titleFont, Brushes.Black, leftMargin, yPos);
                yPos += titleFont.GetHeight(e.Graphics) * 2;

                // 计算每页可打印的行数
                int linesPerPage = (int)((e.MarginBounds.Height - titleFont.GetHeight(e.Graphics) * 2) / lineHeight);
                int linesOnThisPage = 0;

                // 打印文本内容
                while (printLineIndex < printLines.Length && linesOnThisPage < linesPerPage)
                {
                    string line = printLines[printLineIndex];

                    // 检查是否需要换行（行太长）
                    SizeF textSize = e.Graphics.MeasureString(line, printFont);
                    if (textSize.Width > e.MarginBounds.Width)
                    {
                        // 分割长行
                        int charsPerLine = (int)(line.Length * e.MarginBounds.Width / textSize.Width) - 5;
                        if (charsPerLine > 0)
                        {
                            string subLine = line.Substring(0, Math.Min(charsPerLine, line.Length));
                            e.Graphics.DrawString(subLine, printFont, Brushes.Black, leftMargin, yPos);

                            if (line.Length > charsPerLine)
                            {
                                printLines[printLineIndex] = line.Substring(charsPerLine);
                            }
                            else
                            {
                                printLineIndex++;
                            }
                        }
                        else
                        {
                            e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
                            printLineIndex++;
                        }
                    }
                    else
                    {
                        e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
                        printLineIndex++;
                    }

                    yPos += lineHeight;
                    linesOnThisPage++;
                }

                // 判断是否还有更多页需要打印
                e.HasMorePages = (printLineIndex < printLines.Length);
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"打印过程中发生错误：{ex.Message}");
                e.HasMorePages = false;
            }
        }
        #endregion

        #region 事件处理
        /// <summary>
        /// 刷新按钮事件
        /// </summary>
        private async void BtnRefresh_Click(object sender, EventArgs e)
        {
            await LoadMeasurementResultsSummaryAsync();
            UIMessageBox.ShowSuccess("测量结果汇总已刷新！");
        }

        /// <summary>
        /// 导出汇总报告按钮事件
        /// </summary>
        private void BtnDownloadSummary_Click(object sender, EventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                    DefaultExt = "txt",
                    FileName = $"所有通道测量结果汇总_{DateTime.Now:yyyyMMdd_HHmmss}.txt"
                };

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(saveFileDialog.FileName, txtSummaryDisplay.Text, Encoding.UTF8);
                    UIMessageBox.ShowSuccess($"测量结果汇总已保存到：\n{saveFileDialog.FileName}");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"保存文件失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 打印按钮事件
        /// </summary>
        private void BtnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtSummaryDisplay.Text))
                {
                    UIMessageBox.ShowWarning("没有可打印的内容，请先加载数据！");
                    return;
                }

                // 准备打印数据
                printLines = txtSummaryDisplay.Text.Split('\n');
                printLineIndex = 0;

                // 显示打印对话框
                PrintDialog printDialog = new PrintDialog
                {
                    Document = printDocument,
                    UseEXDialog = true
                };

                if (printDialog.ShowDialog() == DialogResult.OK)
                {
                    printDocument.Print();
                    UIMessageBox.ShowSuccess("打印任务已发送到打印机！");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"打印失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 窗体关闭时清理资源
        /// </summary>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            printDocument?.Dispose();
            base.OnFormClosed(e);
        }
        #endregion
    }
}